###################################
### R Function: fsQCA.anchor.ka ###
###################################

fsQCA.anchor.ka=function(raw.data, depvar, indepvars, n.cut, reps, explain, error.reps, given.incl.cut0, given.incl.cut1, min, devs){
  
  fun.threshgen=function(d){
    draw=matrix(data=runif(n=ncol(raw.data)*nrow(raw.data), min=1-d, max=1+d), nrow=nrow(raw.data), ncol=ncol(raw.data))
    out=as.data.frame(raw.data*draw)
    out[floor(out)==1]<-1
    return(out)
  }
 
  fun.error=function(x){
    out=as.data.frame(fsQCA.sim.inclcut(dataset=x, depvar=depvar, indepvars=indepvars, n.cut=n.cut, reps=reps, explain=explain, min=min))
    return(out)
  }
  
  for(i in devs){
    datasets=rlply(.n=error.reps, .expr=fun.threshgen(d=i))
    out=lapply(X=datasets, FUN=fun.error)
    results=rbind.fill(out)
    Configurations=do.call(paste, as.data.frame(results[,4:ncol(results)], stringsAsFactors=FALSE))
    Configurations=gsub(pattern=" NA", replacement="", x=Configurations)
    Configurations=gsub(pattern=" ", replacement=" + \n  ", x=Configurations)
    results=cbind(results[,1:3], paste("Measurement Error = ", i, sep=""), Configurations)
    colnames(results)[4]="error"
    results$incl.cut1.val=as.numeric(as.vector(results$incl.cut1.val))
    results$incl.cut0.val=as.numeric(as.vector(results$incl.cut0.val)) 
    assign(paste("xxxxx.error", i, sep="."), results)
  }
  
  results=lapply(ls(pattern="xxxxx.error"), function(x) get(x))
  results=rbind.fill(results) 
  
  plot=ggplot(data=results, aes(x=incl.cut0.val, y=incl.cut1.val, colour=Configurations))+geom_point()+scale_color_hue(c=150, l=60)+xlim(0,1)+ylim(0,1)+xlab(label="Maximum Sufficiency Inclusion Score")+ylab(label="Minimum Sufficiency Inclusion Score")+geom_point(x=given.incl.cut0, y=given.incl.cut1, shape=17, color="black", size=2)+guides(col=guide_legend(keyheight=2))+facet_wrap(~error, ncol=2)
  
  return(list("results"=results, "plot"=plot))  
  
}